<template>
  <div class="slider" ref="slider">
    <div class="slider-group" ref="sliderGroup">
      <slot>
      </slot>
    </div>
    <div class="dots">
      <span class="dot" :class="{active: currentPageIndex === index }" v-for="(item, index) in dots" :key="index"></span>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import {addClass} from 'common/js/dom'
import BScroll from 'better-scroll'

export default {
  name: 'slider',
  props: {
    loop: {
      type: Boolean,
      default: true
    },
    autoPlay: {
      type: Boolean,
      default: true
    },
    interval: {
      type: Number,
      default: 4000
    }
  },
  data() {
    return {
      dots: [],
      // 表示当前的第几页
      currentPageIndex: 0
    }
  },
  mounted() {
    // 确保dom渲染成功后加载
    setTimeout(() => {
      this._setSliderWidth()
      this._initDots()
      this._initSlider()

      if (this.autoPlay) {
        this._play()
      }
    }, 20)
    // 监听窗口变化事件，窗口变化时，better-scrollDOM变化
    window.addEventListener('resize', () => {
      if (!this.slider) {
        return
      }
      this._setSliderWidth(true)
      this.slider.refresh()
    })
  },
  destroyed() {
    clearTimeout(this.timer)
  },
  methods: {
    // 获得slider宽度
    _setSliderWidth(isResize) {
      // 获得slinderGroup下的所有子节点
      this.children = this.$refs.sliderGroup.children
      let width = 0
      // clientWidth：对象内容的可视区的宽度
      // 不包滚动条等边线，会随对象显示大小的变化而改变
      let sliderWidth = this.$refs.slider.clientWidth
      for (let i = 0; i < this.children.length; i++) {
        // 循环子节点，给每个子节点（这里是img）加一个样式类
        let child = this.children[i]
        addClass(child, 'slider-item')

        // 给每个child节点加一个宽度，使每张图片都为它父节点宽度
        child.style.width = sliderWidth + 'px'
        // 计算所有图片累加的宽度
        width += sliderWidth
      }
      // 如果开启了循环，需要在左右克隆2个DOM，确保可以循环
      // 所以开启循环后，总宽度要增加2个视口宽度
      if (this.loop && !isResize) {
        width += 2 * sliderWidth
      }
      // 最后给父节点最后总宽
      this.$refs.sliderGroup.style.width = width + 'px'
    },
    // 进行betterscroll配置
    _initSlider() {
      this.slider = new BScroll(this.$refs.slider, {
        scrollX: true,
        scrollY: false,
        momentum: false,
        snap: true,
        snapLoop: this.loop,
        snapThreshold: 0.3,
        snapSpeed: 400
      })
      // 滚动结束后的事件
      this.slider.on('scrollEnd', () => {
        // 获得当前第几页
        let pageIndex = this.slider.getCurrentPage().pageX
        if (this.loop) {
          pageIndex -= 1
        }
        this.currentPageIndex = pageIndex

        if (this.autoPlay) {
          clearTimeout(this.timer)
          this._play()
        }
      })
    },
    // 获得真正子节点数
    _initDots() {
      this.dots = new Array(this.children.length)
    },
    // 自动播放功能
    _play() {
      let pageIndex = this.currentPageIndex + 1
      if (this.loop) {
        pageIndex += 1
      }
      this.timer = setTimeout(() => {
        this.slider.goToPage(pageIndex, 0, 400)
      }, this.interval)
    }
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"

  .slider
    min-height: 1px
    .slider-group
      position: relative
      overflow: hidden
      white-space: nowrap
      .slider-item
        float: left
        box-sizing: border-box
        overflow: hidden
        text-align: center
        a
          display: block
          width: 100%
          overflow: hidden
          text-decoration: none
        img
          display: block
          width: 100%
    .dots
      position: absolute
      right: 0
      left: 0
      bottom: 12px
      text-align: center
      font-size: 0
      .dot
        display: inline-block
        margin: 0 4px
        width: 8px
        height: 8px
        border-radius: 50%
        background: $color-text-l
        &.active
          width: 20px
          border-radius: 5px
          background: $color-text-ll
</style>